import React, { memo, useRef, useState } from 'react'
import type { ElementRef, FC, ReactNode } from 'react'
import { shallowEqual } from 'react-redux'
import { BannerControl, BannerLeft, BannerRight, BannerWrapper } from './styled'
import { useAppSelector } from '@/store'
import { Carousel } from 'antd'
import classNames from 'classnames'

interface Iprops {
  children?: ReactNode
}

const TopBanner: FC<Iprops> = () => {
  const [curIndex, setCurIndex] = useState(0)
  // 从store中获取数据
  const banners = useAppSelector(
    (state) => state.recommend.banners,
    shallowEqual
  )
  // banner left right btn event
  // 绑定组件类型
  const bannerRef = useRef<ElementRef<typeof Carousel>>(null)
  function handlePrevClick() {
    bannerRef.current?.prev()
  }
  function handleNextClick() {
    bannerRef.current?.next()
  }
  // AfterChange函数处理

  function handleAfterChange(current: number) {
    setCurIndex(current)
  }
  // 获取背景图片
  let bannerImgUrl = null
  // 拼接背景模糊处理
  if (curIndex >= 0 && banners.length > 0) {
    bannerImgUrl = banners[curIndex]?.imageUrl + '?imageView&blur=40x20'
  }

  function handleBeforeChange() {
    setCurIndex(-1)
  }
  return (
    <BannerWrapper
      style={{ background: `url(${bannerImgUrl}) center center / 6000px` }}
    >
      <div className="banner wrap-v2">
        <BannerLeft>
          {/* 轮博的图片：1.离开时渐变动画：opacity 1.0 -> .2 2.进入的时候没有渐变：切换背景同时直接显示图片 */}
          {/* antd提供的轮播：离开时有渐变，进入时也有渐变 */}
          {/* 想要达到这个效果可以自定义轮播图 */}
          <Carousel
            autoplay
            ref={bannerRef}
            afterChange={handleAfterChange}
            beforeChange={handleBeforeChange}
            dots={false}
            waitForAnimate={true}
          >
            {banners.map((item) => {
              return (
                <div className="item" key={item.imageUrl}>
                  <img
                    className="image"
                    src={item.imageUrl}
                    alt={item.typeTitle}
                  />
                </div>
              )
            })}
          </Carousel>
          <ul className="dots">
            {banners.map((item, index) => {
              return (
                <li key={item.imageUrl}>
                  <span
                    className={classNames('item', {
                      active: curIndex === index
                    })}
                  ></span>
                </li>
              )
            })}
          </ul>
        </BannerLeft>
        <BannerRight>
          <p>PC 安卓 iPhone WP iPad Mac 六大客户端</p>
        </BannerRight>
        <BannerControl>
          <button className="btn left" onClick={handlePrevClick}></button>
          <button className="btn right" onClick={handleNextClick}></button>
        </BannerControl>
      </div>
    </BannerWrapper>
  )
}
export default memo(TopBanner)
